<template>
  <div>
    <div class="flex">
      <van-image
        class="mr-2"
        width="50px"
        height="50px"
        fit="cover"
        round
        v-if="isAvatar"
        :src="userInfo.avatarUrl"
      />
      <div class="w-full">
        <div
          @focus="focusChange"
          @blur="blurChange"
          v-html="commentValue"
          contenteditable="true"
          name=""
          id="inputID"
          ref="inputRef"
          tabindex="0"
          class="
            min-h-[80px]
            block
            p-1
            w-full
            outline-0
            bg-zinc-100
            caret-zinc-400
            rounded
            text-zinc-900
            tracking-wide
            text-sm
            font-semibold
            border border-zinc-100
            duration-500
            focus:bg-white focus:border-blue-500
          "
        ></div>
        <div class="w-full flex justify-between mt-2 items-center submitBtn">
          <div class="flex items-center">
            <x-popover direction="right">
              <Emotion @seleIcon="seleIcon"></Emotion>
              <template #reference>
                <button
                  type="button"
                  @click="focusDiv"
                  class="
                    text-zinc-500 text-base
                    cursor-pointer
                    mr-2
                    flex
                    items-center
                  "
                >
                  <van-icon name="smile-o" size="20" />
                  <span class="ml-0.5"> 表情 </span>
                </button>
              </template>
            </x-popover>
            <div
              class="text-zinc-500 text-base cursor-pointer flex items-center"
            >
              <van-icon name="photo-o" size="20" />
              <span class="ml-0.5"> 图片(TODO) </span>
            </div>
          </div>
          <van-button size="small" round type="primary" @click="sendComment"
            >发表评论</van-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { Toast } from "vant";
import { postComment } from "@/api/comment.js";
import Emotion from "@/components/Emotion.vue";
const props = defineProps({
  postid: {
    type: [Number, String],
    default: "",
  },
  replyid: {
    type: [Number, String],
    default: "",
  },
  pid: {
    type: [Number, String],
    default: "",
  },
  isAvatar: {
    type: Boolean,
    default: true,
  },
});
const info = localStorage.getItem("userinfo");
const userInfo = ref(JSON.parse(info));
const inputRef = ref(null);
const emits = defineEmits(["sendComment", "blurChange", "focusChange"]);
const blurChange = () => {
  // console.log("失去焦点 :>> ", window.getSelection().focusNode.id);
  emits("blurChange");
};
// const target = ref(null);
// onClickOutside(target, (event) => {
//   console.log(event);
// });
const focusChange = () => {
  // console.log("获取焦点 :>> ", window.getSelection().focusNode.id);
  emits("focusChange");
};
const focusDiv = () => {
  inputRef.value.focus();
};
const seleIcon = (html) => {
  let sel, range;
  if (window.getSelection) {
    // IE9及其它浏览器
    sel = window.getSelection();
    if (!sel.focusNode || sel.focusNode.id !== "inputID") {
      inputRef.value.focus();
      document.execCommand("selectAll", false, null);
      document.getSelection().collapseToEnd();
    }
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      let el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment();
      var node;
      var lastNode;

      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      range.insertNode(frag);

      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if (document.selection && document.selection.type != "Control") {
    // IE < 9
    document.selection.createRange().pasteHTML(html);
  }
};

const commentValue = ref("");

const sendComment = async () => {
  if (!inputRef.value.innerHTML) {
    Toast("请输入评论内容!");
    return;
  }
  await postComment({
    content: inputRef.value.innerHTML,
    postid: props.postid,
    pid: props.pid,
    replyid: props.replyid,
  });
  inputRef.value.innerHTML = "";
  Toast.success("评论成功!");
  emits("sendComment");
};
defineExpose({ focusDiv });
</script>

<style>
/*  */
#inputID:empty:before {
  content: "说点什么好呢？";
  color: gray;
}
#inputID:focus:before {
  content: none;
}
</style>